﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EntityFramework.Extensions;
using Kugar.Core.BaseStruct;
using Kugar.Core.ExtMethod;
using Kugar.Core.Network.Web;
using WS.FlowAuth.Web.Data.DTO;
using WS.FlowAuth.Web.Data.EF;

namespace WS.FlowAuth.Web.BLL
{
    public class UserManager:BaseManager
    {
        private RequestThreadLocal<base_User> _currentUserID = new RequestThreadLocal<base_User>();

        public VM_PagedList<base_User> GetUserList(string keyword, int pageIndex = 1, int pageSize = 20)
        {
            return Context.base_User.Where(x => (keyword == "" || x.UserName.Contains(keyword)) && !x.IsDeleted)
                .GetPagedList(pageIndex, pageSize);
        }

        public base_User GetUserByID(int userID)
        {
            return Context.base_User.FirstOrDefault(x => x.UserID == userID);
        }

        public base_User GetUserByUserNamePassword(string userName, string password)
        {
            password = password.MD5_32();

            return Context.base_User.FirstOrDefault(x => x.UserName == userName && x.Password == password);
        }

        public base_User[] GetUserByIDs(int[] userIDs)
        {
            if (!userIDs.HasData())
            {
                return new base_User[0];
            }

            return Context.base_User.Where(x => userIDs.Contains(x.UserID)).ToArrayEx();
        }

        public ResultReturn<int> AddUser(string userName, string password)
        {
            if (string.IsNullOrWhiteSpace(userName))
            {
                return new FailResultReturn<int>("用户名不能为空");
            }

            if (Context.base_User.Any(x=>x.UserName==userName))
            {
                return new FailResultReturn<int>("用户名不能重复");
            }

            try
            {
                var item = new base_User()
                {
                    UserName = userName,
                    Password = password.MD5_32(),
                    CreateDt = DateTime.Now,
                    State = 0,
                    IsDeleted = false,
                    IsSystem = false
                };

                Context.base_User.Add(item);

                if (Context.SaveChanges() > 0)
                {
                    return new SuccessResuleReturn<int>(item.UserID);
                }
                else
                {
                    return new FailResultReturn<int>("添加用户失败");
                }
            }
            catch (Exception e)
            {
                return new FailResultReturn<int>(e);
            }
        }

        public ResultReturn UpdateUserState(int userID, int state)
        {
            try
            {
                Context.base_User.Where(x => x.UserID == userID).Update(x => new base_User()
                {
                    State = state
                });

                return SuccessResuleReturn.Default;
            }
            catch (Exception e)
            {
                return new FailResultReturn(e);
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="newPassword"></param>
        /// <returns></returns>
        public ResultReturn ResetUserPassword(int userID, string newPassword)
        {
            try
            {
                Context.base_User.Where(x => x.UserID == userID)
                    .Update(x => new base_User()
                    {
                        Password = newPassword.MD5_32()
                    });

                return SuccessResuleReturn.Default;
            }
            catch (Exception e)
            {
                return new FailResultReturn(e);
            }
        }

        /// <summary>
        /// 用户自行修改密码,使用旧密码修改
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="oldPasswrod"></param>
        /// <param name="newpassword"></param>
        /// <returns></returns>
        public ResultReturn ResetUserPassword(int userID, string oldPasswrod, string newpassword)
        {
            try
            {
                oldPasswrod = oldPasswrod.MD5_32();
                
                if (!Context.base_User.Any(x=>x.UserID==userID && x.Password==oldPasswrod))
                {
                    return new FailResultReturn("旧用户名错误");
                }

                return ResetUserPassword(userID, newpassword);
            }
            catch (Exception e)
            {
                return new FailResultReturn(e);
            }
        }

        /// <summary>
        /// 标识用户为删除
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public ResultReturn DeleteUser(int userID)
        {
            try
            {
                Context.base_User.Where(x => x.UserID == userID).Update(x => new base_User()
                {
                    IsDeleted = true
                });

                return SuccessResuleReturn.Default;
            }
            catch (Exception e)
            {
                return new FailResultReturn(e);
            }
        }
        
        /// <summary>
        /// 当前用户
        /// </summary>
        public base_User CurrentUser
        {
            get { return _currentUserID.IsValueCreated ? _currentUserID.Value : null; }
            set { _currentUserID.Value = value; } 
        }
    }
}
